import urllib.request as ur
import urllib.parse as up
import json

while True:
    kw=(input('请输入翻译的内容：'))     # 输入你要翻译的单词

    data={
        'kw':kw
    }

    data_url=up.urlencode(data)         # 将data作为URL查询字符串

    #封装Request对象
    request = ur.Request(
        url = 'https://fanyi.baidu.com/sug',
        data = data_url.encode('utf-8')         #把url编码转成字节
    )

    response = ur.urlopen(request).read()       # 获得查询结果

    ret = json.loads(response)      #json对象转化为python对象

    # 增加代码健硕性
    try:
        keys = ret['data'][0]['k']
        values = ret['data'][0]['v']
        print(keys,values)
    except:
        print('未查到相关结果，请规范您的输入！')







